package com.study.spmongodb.wwj.juc.utils;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/13 9:24
 */
public class CyclicBarrierExample {

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {

        final CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> System.out.println("all task finished"));
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println("t1 finished");
                cyclicBarrier.await();
                System.out.println("the other thread finished  ");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println("t2 finished");
                cyclicBarrier.await();
                System.out.println("the other thread finished too");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }).start();

        // cyclicBarrier.await();
        // System.out.println("all task finished.");
        System.out.println(cyclicBarrier.getNumberWaiting());
        System.out.println(cyclicBarrier.getParties());
    }
}
